// pages/personal/order/order.js
const numeral = require('../../../vendor/numeral/numeral.min')
let scrollLeft = 0
const app = getApp()
let paying = false
const pool = new Map()


const orderActions = [
    { name: "申请退款", method: "payBack", style: "" },
    { name: "查看物流", method: "kd", style: "" },
    { name: "确认收货", method: "submit", style: "background:#E64340;color:#fff;border-color:#E64340" },
    { name: "立即评价", method: "comment", style: "" },
    { name: "查看评论", method: "viewComment", style: "" },
    { name: "删除订单", method: "delOrder", style: "" },
    { name: "立即支付", method: "pay", style: "background:#E64340;color:#fff;border-color:#E64340" },
]
function findAction() {
    return orderActions.filter(o => {
        return Array.from(arguments).indexOf(o.name) >= 0
    })
}
function getOrderAction(item) {
    const status = parseInt(item.status)
    let r = []
    switch (status) {
        case 0:
            r = findAction("立即支付")
            break
        case 10:
            break
        case 40:
            r = findAction("查看物流", "确认收货")
            break
        case 60:
            r = findAction("立即评价")
            break
        case 61:
            r = findAction("查看评论")
            break
    }
    return r
}
Page({
    data: {},
    onLoad(options) {
        this.setData(options)
        pool.clear()
        app.http.get("order/status-dict", {}).then(res => {
            let tabs = [
                { name: "全部", status: 1 },
                { name: "待支付", status: res.data.STATU_WAIT_PAY.code },
                { name: "待成团", status: res.data.STATU_GROUP_PURCHASE.code },
                { name: "抽奖", status: res.data.STATU_WAITING_FOR_LOTTERY.code },
                { name: "待发货", status: res.data.STATU_WAIT_FOR_DELIVERY.code },
                { name: "待收货", status: res.data.STATU_WAIT_FOR_SIGN.code },
                { name: "待评价", status: res.data.STATU_WAIT_EVALUATION.code },
            ]
            this.statusDict = res.data
            let statusObj = {}
            Object.keys(res.data).forEach(k => {
                statusObj[res.data[k].code] = res.data[k].name
            })
            this.setData({
                statusObj,
                tabs,
                status: options.status || tabs[0].status,

            })
            this.loadData()
        })
    },

    loadData() {
        let tab = pool.get(this.data.status)
        if (!tab) {
            tab = { page: 1, total: 2, list: [] }
            pool.set(this.data.status, tab)
        }
        this.setData(tab)
        if (tab.page > tab.total) {
            this.setData(tab)
            return
        }

        if (tab.page == 1) {
            wx.showLoading({
                title: '加载中...',
            })
        }

        if (this.data.loading) {
            return
        }

        this.setData({
            loading: true
        })

        app.http.get("member/order-list", {
            data: { status: this.data.status, page: tab.page }
        }).then(res => {
            res.data.data.forEach(o => {
                o.total_money = numeral((o.express_cost + o.total_cost - o.express_cost) / 100).format('0,0.00')
                o.express_money = numeral(o.express_cost / 100).format("0,0.00")
                let acs = getOrderAction(o)
                if (o.type == 2 && o.status != this.statusDict.STATU_WAIT_PAY.code) {
                    acs.splice(acs.length - 1, 0, { name: "团详情", method: "groupDetail", })
                }
                o.isWon = 0

                if (o.type == 3) {
                    acs.splice(acs.length - 1, 0, { name: "详 情", method: "luckyDetail", })
                    if (o.status != this.statusDict.STATU_WAITING_FOR_LOTTERY.code) {
                        o.isWon = o.luckyOrder ? 1 : -1
                    }
                }
                if (o.status == 0) {
                    //未支付的订单 允许用户删除
                    acs.unshift({ name: "删除订单", method: "delOrder", style: "opacity:.8" })
                }

                if (acs.length > 3) {
                    o.moreActions = acs.slice(0, acs.length - 3)
                    acs = acs.slice(-3)
                }
                o.actions = acs
                o.goodsOrderItems.money = numeral(o.goodsOrderItems.price / 100).format("0,0.00")

            })
            tab.list.push(...res.data.data)
            tab.page++
            tab.total = res.data.total
            this.setData(tab)
            wx.hideLoading()
            wx.stopPullDownRefresh()
            this.setData({
                loading: false
            })
        }).catch(err => {
            app.wxToast.error(err.message)
            this.setData({
                loading: false
            })
            console.log(err)
        })
    },

    onPullDownRefresh() {
        let tab = pool.get(this.data.status)
        tab.page = 1
        tab.total = 2
        tab.list = []
        this.loadData()
    },

    onShow() {
        // pool.clear()
        // if (this.data.tabs) {
        //     this.loadData()
        // }
    },

    onScroll(evt) {
        scrollLeft = evt.detail.scrollLeft
    },
    onReachBottom() {
        this.loadData()
    },


    clickTab(evt) {
        const status = evt.currentTarget.dataset.status
        if (status != this.data.status) {
            this.setData({
                status
            })
            let tab = pool.get(this.data.status)
            if (tab && tab.list.length == 0) {
                tab.page = 1
                tab.total = 2
            }
            this.loadData()
        }
    },




    delOrder(evt) {
        const { id, index } = evt ? evt.currentTarget.dataset : arguments[1]
        let tab = pool.get(this.data.status)
        app.toPromise(wx.showModal, {
            title: "提示",
            content: '是否删除该订单？',
        }).then(res => {
            if (res.confirm) {
                wx.showLoading({
                    title: '删除中...',
                })
                app.http.get("member/delete", {
                    data: { id: id },
                }).then(r => {
                    tab.list.splice(index, 1)
                    this.setData(tab)
                    wx.hideLoading()
                    setTimeout(() => {
                        wx.showToast({
                            title: '订单已删除',
                        })
                    }, 0)

                }).catch(err => {
                    app.wxToast.error(err.message)
                })
            }
        })
    },



    submit(evt) {
        const { id, index } = evt ? evt.currentTarget.dataset : arguments[1]
        wx.showModal({
            title: '提示',
            content: '请确认您已收到物品，并且包装无损坏，如有问题，请拒绝签收。',
            confirmText: "确认收货",
            success: res => {
                if (res.confirm) {
                    wx.showLoading({
                        title: '加载中...',
                    })
                    app.http.get("member/take-over", {
                        data: { id },
                    }).then(res => {
                        wx.hideLoading()
                        this.onPullDownRefresh()
                    }).catch(err => {
                        app.wxToast.error(err.message)
                    })
                } else {

                }
            }
        })
    },

    pay(evt) {
        const { id, index } = evt ? evt.currentTarget.dataset : arguments[1]
        let ct = pool.get(this.data.status).list.find(o => o.id == id)
        wx.showLoading({
            title: '加载中...',
        })
        app.http.get("member/pay-again", {
            data: { id },
        }).then(res => {
            wx.hideLoading()
            wx.requestPayment(Object.assign({
                success: res => {
                    this.onPullDownRefresh()
                },
                fail: err => {
                    app.wxToast.warn("支付失败，请重新支付")
                }
            }, res.data.js))
        }).catch(err => {
            app.wxToast.warn(err.message)
        })
    },

    payBack(evt) {
        let id = evt.currentTarget.dataset.id
        let tab = pool.get(this.data.status)
        app.toPromise(wx.showModal, {
            title: "提示",
            content: '确认要申请退货吗？',
        }).then(res => {
            if (res.confirm) {
                wx.showLoading({
                    title: '删除中...',
                })

                app.http.get("order/apply-return", {
                    data: { id },
                }).then(result => {

                }).catch(err => {
                    app.wxToast.error(err.message)
                })
            }
        })
    },
    comment(evt) {
        const { id, index } = evt ? evt.currentTarget.dataset : arguments[1]
        const order = this.data.list[index]
        app.tmpGoods = order.goodsOrderItems
        wx.navigateTo({ url: './comment?id=' + id })
    },
    viewComment(evt) {
        const { id, index } = evt ? evt.currentTarget.dataset : arguments[1]
        const order = this.data.list[index]
        app.tmpGoods = order.goodsOrderItems
        wx.navigateTo({ url: './comment?check=1&id=' + id })
    },
    viewLog(evt) {
        wx.navigateTo({
            url: './logistics',
        })
    },
    //团详情
    groupDetail(evt) {
        wx.navigateTo({
            url: '/pages/pt/ok/ok?id=' + evt.currentTarget.dataset.id,
        })
    },

    //物流
    kd(evt) {
        const { id, index } = evt ? evt.currentTarget.dataset : arguments[1]
        const order = this.data.list[index]
        wx.navigateTo({
            url: './logistics?id=' + id
        })
    },


    moreAction(evt) {
        const { id, index } = evt.currentTarget.dataset
        const obj = this
        wx.showActionSheet({
            itemList: this.data.list[index].moreActions.map(o => o.name),
            success: res => {
                obj[this.data.list[index].moreActions[res.tapIndex].method](evt)
            }
        })
    },

    //抽奖详情
    luckyDetail(evt) {
        const { id, index } = evt.currentTarget.dataset
        wx.navigateTo({
            url: '/pages/goods/lucky?id=' + this.data.list[index].luckyMainOrder.lucky.id,
        })
    }
})
